'use strict';

const BaseController = require('./base');

class UserRelationController extends BaseController {
  get _service() {
    return 'userRelation';
  }

  // 判断是否关注过
  async isFollow() {
    const { ctx } = this;
    const { followId } = ctx.params();
    const isExist = await this._getService().isExist({ uid: ctx.userId, followId });
    if (isExist) {
      this.success({ flag: true });
    } else {
      this.success({ flag: false });
    }
  }

  async create() {
    const { ctx } = this;
    const { followId } = ctx.params();
    const isExist = await this._getService().isExist({ uid: ctx.userId, followId, paranoid: false });
    let result = null;
    if (isExist) {
      result = await this._getService().restore({ uid: ctx.userId, followId });
    } else {
      result = await this._getService().create({ uid: ctx.userId, followId });
    }
    if (result) {
      this.success();
    } else {
      this.error('关注失败');
    }
  }

  async destroy() {
    const { ctx } = this;
    const { followId } = ctx.request.body;
    const result = await this._getService().destory({ followId, uid: ctx.userId });
    if (result) {
      this.success();
    } else {
      this.error('取消关注失败');
    }
  }

  // 获取所有关注
  async index() {
    const { ctx } = this;
    const { prop, sort, pageIndex, pageSize } = ctx.params();
    const { createdAt } = ctx.queries;
    const tempResult = await this._getService().findList({ prop, sort, pageIndex, pageSize, createdAt });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取关注失败');
    }
  }

  // 获取登录人的关注
  async indexMy() {
    const { ctx } = this;
    const { pageIndex, pageSize } = ctx.params();
    const tempResult = await this._getService().findList({ uid: ctx.userId, pageIndex, pageSize });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取关注失败');
    }
  }

  // 获取登录人的粉丝
  async indexMyFollow() {
    const { ctx } = this;
    const { pageIndex, pageSize } = ctx.params();
    const tempResult = await this._getService().findList({ followId: ctx.userId, pageIndex, pageSize });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取关注失败');
    }
  }

  // 获取他人的关注
  async show() {
    const { ctx } = this;
    const { pageIndex, pageSize } = ctx.params();
    const { id } = ctx.params;
    const tempResult = await this._getService().findList({ followId: id, pageIndex, pageSize });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取关注失败');
    }
  }
}

module.exports = UserRelationController;
